﻿#define _CRT_SECURE_NO_WARNINGS	

#include"List.h"


//LTNode* LTInit();
LTNode* LTBuyNode(LTDataType x)
{
	
	LTNode* newnode = (LTNode*)malloc(sizeof(LTNode));

	if (newnode == NULL)
	{
		perror("malloc fail");
		exit(EXIT_FAILURE);
	}

	newnode->next = newnode;
	newnode->prev = newnode;

	newnode->data = x;

	return newnode;
}

//对双向链表的初始化，就是为双向链表创建“哨兵位”（头节点）
void LTInit(LTNode** pphead)
{
	*pphead = LTBuyNode(-1); //这里是象征性的给值，实际上头节点是不存储有效的数据的
}

void LTDestroy(LTNode* phead)
{
	LTNode* pcur = phead->next;
	while (pcur != phead)
	{
		LTNode* next = pcur->next;
		free(pcur);
		pcur = next;
	}
	free(phead);
	pcur = NULL;
	phead = NULL;
}

void LTPrint(LTNode* phead)
{
	assert(phead);

	LTNode* pcur = phead->next;

	while (pcur != phead)
	{
		printf("%d->",pcur -> data);
		pcur = pcur->next;
	}
	printf("\n");
}

bool LTEmpty(LTNode* phead)
{
	if (phead->next == phead)
	{
		return true;
	}

	return false;

}

void LTPushBack(LTNode* phead, LTDataType x)
{
	assert(phead);
	
	LTNode* tail = phead->prev;

	LTNode* newnode = LTBuyNode(x);

	newnode->next = phead;
	newnode->prev = tail;

	tail->next = newnode;
	phead->prev = newnode;
}

void LTPopBack(LTNode* phead)
{
	assert(phead && phead->next);

	LTNode* tail = phead->prev->prev;

	free(tail->next);
	//phead phead->prev phead->prev->prev
	tail->next = phead;
	phead->prev = tail;
	
}

void LTPushFront(LTNode* phead, LTDataType x)
{
	assert(phead);

	//在第一个有效数据前插入
	//如果是在头节点前插入的话，就变成尾插的了
	LTNode* pcur = phead->next;

	LTNode* newnode = LTBuyNode(x);

	newnode->next = pcur;
	newnode->prev = phead;

	phead->next = newnode;
	pcur->prev = newnode;

}

void LTPopFront(LTNode* phead)
{
	assert(phead && phead->next);

	LTNode* del = phead->next;

	phead->next = del->next;
	del->prev = phead;

	free(del);
	del = NULL;
}

//在pos位置之后插⼊数据
void LTInsert(LTNode* pos, LTDataType x)
{
	assert(pos);

	LTNode* newnode = LTBuyNode(x);

	newnode->next = pos->next;
	newnode->prev = pos;

	newnode->next->prev = newnode;
	pos->next = newnode;

}

void LTErase(LTNode* pos)
{
	assert(pos);

	LTNode* prev = pos->prev;
	LTNode* next = pos->next;

	prev->next = next;
	next->prev = prev;

	free(pos);
	pos = NULL;
}

LTNode* LTFind(LTNode* phead, LTDataType x)
{
	assert(phead && phead->next);

	LTNode* pcur = phead->next;
	while (pcur != phead)
	{
		if (pcur->data == x)
		{
			return pcur;
		}
		pcur = pcur->next;
	}

	return NULL;
}